const _ = require('lodash');
module.exports = (db, DataTypes) => {
  let Charging = db.define('Charging', {
    code: {
      type: DataTypes.CHAR(20),
      allowNull: false,
      primaryKey: true,
    },
    '0x31': DataTypes.TEXT('medium'),
    '0x34': DataTypes.TEXT('medium'),
    '0x39': DataTypes.TEXT('medium'),
    accessed_at: {
      type: DataTypes.BIGINT(13).UNSIGNED,
      allowNull: false,
      defaultValue: 0,
    },
    created_at: {
      type: DataTypes.BIGINT(13).UNSIGNED,
      allowNull: false,
      defaultValue: 0,
    },
    updated_at: {
      type: DataTypes.BIGINT(13).UNSIGNED,
      allowNull: false,
      defaultValue: 0,
    },
  }, {
    timestamps: false,
    freezeTableName: true,
    tableName: 'chargings'
  });
  Charging.sync();
  // 类方法
  Charging.access = function (code) {
    return Charging.upsert({
      code: code,
      accessed_at: _.now(),
      created_at: _.now(),
      updated_at: _.now(),
    }, {
      fields: ['accessed_at', 'updated_at']
    });
  };

  Charging.savePacket = function (code, type, data) {
    let o = {
      code: code,
      accessed_at: _.now(),
      created_at: _.now(),
      updated_at: _.now(),
    };
    o[type] = JSON.stringify(data);
    return Charging.upsert(o, {
      fields: [type, 'accessed_at', 'updated_at']
    });
  };
  return Charging;
};
